package com.dayu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dayu.common.exception.NoStockException;
import com.dayu.common.utils.R;
import com.dayu.common.vo.MemberResponseVo;
import com.dayu.gulimall.order.dao.OrderItemDao;
import com.dayu.gulimall.order.entity.OrderItemEntity;
import com.dayu.gulimall.order.feign.CartFeignService;
import com.dayu.gulimall.order.feign.MemberFeignService;
import com.dayu.gulimall.order.feign.ProductFeignService;
import com.dayu.gulimall.order.feign.WareFeignService;
import com.dayu.gulimall.order.intecepter.OrderIntercepter;
import com.dayu.gulimall.order.service.OrderItemService;
import com.dayu.gulimall.order.service.constant.OrderConstant;
import com.dayu.gulimall.order.vo.*;
import feign.RequestInterceptor;
import org.aspectj.weaver.ast.Or;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayu.common.utils.PageUtils;
import com.dayu.common.utils.Query;

import com.dayu.gulimall.order.dao.OrderDao;
import com.dayu.gulimall.order.entity.OrderEntity;
import com.dayu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private static ThreadLocal<OrderSubmitVo> threadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo vo = new OrderConfirmVo();
        MemberResponseVo loginUser = OrderIntercepter.loginUser.get();
        //feign在调用服务的时候，会丢失请求头信息，解决办法：需要自定义请求拦截器
        //feign请求逻辑
//        feign调用服务的时候，会创建一个新的请求头，默认这个请求头没有任何信息，所以在调用的时候必须将老的请求头信息同步到新的请求头上来
//        源代码如下：在构建新的请求的时候，会获取拦截器，如果定义了拦截器，那么就会把拦截器里的信息同步过来
//        while(var2.hasNext()) {
//                    RequestInterceptor interceptor = (RequestInterceptor)var2.next();
//                    interceptor.apply(template);
//                }

        //将主线程中的请求信息，共享到异步编排的线程中，不然拦截器中获取的 request信息不一致
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //远程调用member，获取地址列表
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> addresses = memberFeignService.getAddresses(loginUser.getId());
            vo.setAddress(addresses);
        }, executor);


        CompletableFuture<Void> getCartItemsFuture = CompletableFuture.runAsync(() -> {
            //远程获取所有选中的购物项
            try {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
                vo.setItems(cartItems);
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = vo.getItems();
            if (!CollectionUtils.isEmpty(items)) {
                List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
                RequestContextHolder.setRequestAttributes(requestAttributes);
                //远程调用批量查询是否有库存
                R r = wareFeignService.hasStock(skuIds);
//                r.getData("data", new TypeReference<List<SkuHasStockVo>>() );
                List<SkuHasStockVo> hasStockVos = r.getData("data", new TypeReference<List<SkuHasStockVo>>() {
                });

                if (!CollectionUtils.isEmpty(hasStockVos)) {
                    Map<Long, Boolean> collect = hasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                    vo.setStocks(collect);
                }


            }

        }, executor);


        Integer integration = loginUser.getIntegration();
        vo.setIntegration(integration);

        //其他数据自动计算
        //TODO 重复处理
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX + loginUser.getId(), token, 30, TimeUnit.MINUTES);
        vo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture, getCartItemsFuture).get();
        return vo;
    }

    /**
     * 提交订单
     * 本地事务，只能出异常只能本地回滚，远程方法不回滚
     * 分布式事物，
     * <p>
     * 本地事务，在分布式系统，只能控制住自己的回滚，控制不了其他服务的回滚
     * 分布式事务:最大原因。网络问题+分布式机器。
     * // (isolation = Isolation.REPEATABLE_READ)
     * //REQUIRED、REQUIRES_NEw
     * redis原子性操作
     *
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) throws ExecutionException, InterruptedException {
        threadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        MemberResponseVo loginUser = OrderIntercepter.loginUser.get();
//        1、验证令牌，令牌的对比和删除一定是原子性的
        //0 令牌失败  1、令牌成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        String key = OrderConstant.ORDER_TOKEN_PREFIX + loginUser.getId();
//        原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(key), orderToken);
        if (result == 0L) {
//            验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
//            验证成功
//       下单：创建订单，验证令牌，验证价格，锁库存。。。
            //1.创建订单，订单项等..
            OrderCreateTo order = createOrder();
            //2.验价格
            BigDecimal payPrice = order.getPayPrice();
            BigDecimal payPrice1 = vo.getPayPrice();
            if (Math.abs(payPrice.subtract(payPrice1).doubleValue()) < 0.01) {
                //金额对比
                //3.保存订单
                saveOrder(order);
                //4.锁定库存,只要有异常，就回滚
                OrderLockVo lockVo = new OrderLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);
                R r = wareFeignService.lockOrderStock(lockVo);
                if (r.getCode() == 0) {
                    //锁定成功
                    responseVo.setOrderEntity(order.getOrder());
                    //todo 远程扣减积分，出异常，回滚订单，库存不回滚
                    int a = 10 / 0;
                    return responseVo;
                } else {

                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
//                    responseVo.setCode(3);
//                    return responseVo;
                }
            } else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity entity = order.getOrder();
        entity.setModifyTime(new Date());
//        this.baseMapper.insert(entity);
        this.save(entity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        //保存所有订单项
        orderItemService.saveBatch(orderItems);

    }

    private OrderCreateTo createOrder() throws ExecutionException, InterruptedException {
        OrderCreateTo to = new OrderCreateTo();
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        //1创建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //2获取所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3 验价格
        computerPrice(orderEntity, itemEntities);
        to.setOrder(orderEntity);
        to.setOrderItems(itemEntities);
        to.setPayPrice(orderEntity.getPayAmount());
        to.setFair(orderEntity.getFreightAmount());
        return to;
    }

    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0");
        //优惠券
        BigDecimal coupon = new BigDecimal("0");
        //积分
        BigDecimal integration = new BigDecimal("0");
        //促销价
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal gift = new BigDecimal("0");
        BigDecimal grow = new BigDecimal("0");
        if (!CollectionUtils.isEmpty(itemEntities)) {

            for (OrderItemEntity item : itemEntities) {
                BigDecimal realAmount = item.getRealAmount();
                BigDecimal couponAmount = item.getCouponAmount();
                BigDecimal integrationAmount = item.getIntegrationAmount();
                BigDecimal promotionAmount = item.getPromotionAmount();
                gift.add(new BigDecimal(item.getGiftIntegration().toString()));
                grow.add(new BigDecimal(item.getGiftGrowth().toString()));
                total = total.add(realAmount);
                coupon = coupon.add(couponAmount);
                integration = integration.add(integrationAmount);
                promotion = promotion.add(promotionAmount);
            }

            //订单的价格相关
            orderEntity.setTotalAmount(total);
            //实际支付为总额加运费
            orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
            orderEntity.setPromotionAmount(promotion);
            orderEntity.setIntegrationAmount(integration);
            orderEntity.setCouponAmount(coupon);

            //设置积分信息
            orderEntity.setIntegration(gift.intValue());
            orderEntity.setGrowth(grow.intValue());
            orderEntity.setDeleteStatus(0);
        }
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) throws ExecutionException, InterruptedException {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (!CollectionUtils.isEmpty(currentUserCartItems)) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(item -> {
                OrderItemEntity entity = buildOrderItem(item);
                entity.setOrderSn(orderSn);

                return entity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //spu信息
        R r = productFeignService.getBySkuId(item.getSkuId());
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());

        //sku 信息
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        //将list转换为string，以；为分隔符
        String attrs = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(attrs);
        orderItemEntity.setSkuQuantity(item.getCount());

        //积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());

        //各种优惠金额
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        BigDecimal orignPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orignPrice.subtract(orderItemEntity.getIntegrationAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount());
        orderItemEntity.setRealAmount(subtract);


        return orderItemEntity;
    }

    private OrderEntity buildOrder(String orderSn) {
        OrderEntity entity = new OrderEntity();
        MemberResponseVo loginUser = OrderIntercepter.loginUser.get();
        //会员id
        entity.setMemberId(loginUser.getId());

        OrderSubmitVo submitVo = threadLocal.get();
        R fair = wareFeignService.getFair(submitVo.getAddrId());

        FairVo fairVo = fair.getData(new TypeReference<FairVo>() {
        });
        //设置运费信息
        entity.setFreightAmount(fairVo.getFair());
        //设置收货人信息
        MemberAddressVo address = fairVo.getAddress();
        entity.setReceiverCity(address.getCity());
        entity.setReceiverDetailAddress(address.getDetailAddress());
        entity.setReceiverProvince(address.getProvince());
        entity.setReceiverName(address.getName());
        entity.setReceiverPhone(address.getPhone());
        entity.setReceiverPostCode(address.getPostCode());
        entity.setReceiverRegion(address.getRegion());
        entity.setOrderSn(orderSn);
        entity.setDeleteStatus(0);//未删除
        return entity;
    }


    /**
     * 事物的传播
     */
    @Transactional(timeout = 30)
    public void a() {

        //使用aspectj动态代理 ，创建本类实例，然后调用本类方法，就可以解决事物失效问题
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b(); //新事物，不回滚
        orderService.c();//事物，回滚
    }

    /**
     * 事物
     */
    @Transactional(timeout = 30,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRES_NEW)
    public void b() {

    }

    @Transactional(timeout = 50,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public void c() {

    }


}